package org.springsource.controllers;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.UserProfile;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.WebRequest;
import org.springsource.domain.Account;
import org.springsource.domain.SignupForm;
import org.springsource.service.AccountService;
import org.springsource.signin.SignInUtils;


@Controller
public class SignUpController {
	@Autowired
	private AccountService accountService; 
	
	private static final Logger logger = LoggerFactory.getLogger(SignUpController.class);
	


	@RequestMapping(value="/signup", method=RequestMethod.GET)
	public SignupForm signupForm(WebRequest request) {
		logger.info("in sign up");
		Connection<?> connection = ProviderSignInUtils.getConnection(request);
		if (connection != null) {
			logger.info("not null");
			
			request.setAttribute("message",  "Your " + StringUtils.capitalize(connection.getKey().getProviderId()) + " account is not associated with a Spring Social Showcase account. If you're new, please sign up.", WebRequest.SCOPE_REQUEST);
			UserProfile profile = connection.fetchUserProfile();
			logger.info("first name: "+profile.getFirstName());
			logger.info("user name: "+profile.getUsername());
			return SignupForm.fromProviderUser(connection.fetchUserProfile());
		} else {
			logger.info("null");
			return new SignupForm();
		}
	}

	@RequestMapping(value="/signup", method=RequestMethod.POST)
	public String signup(@Valid SignupForm form, BindingResult formBinding, WebRequest request) {
		if (formBinding.hasErrors()) {
			return null;
		}
		Account account = createAccount(form, formBinding);
		if (account != null) {
			SignInUtils.signin(account.getUsername());
			ProviderSignInUtils.handlePostSignUp(account.getUsername(), request);
			return "redirect:/";
		}
		return null;
	}

	// internal helpers

	private Account createAccount(SignupForm form, BindingResult formBinding) {
			Account account = new Account(form.getUsername(), form.getPassword(), form.getFirstName(), form.getLastName());
			accountService.saveOrUpdate(account);
			return account;
	}
}
